package cn.fengLone.pay.util.aliPay;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import cn.fengLone.pay.entity.AliPayFull;
import cn.fengLone.pay.entity.PayInfo;
import cn.fengLone.pay.exception.BaseException;
import cn.fengLone.pay.util.SimpleUtil;
import cn.fengLone.pay.util.SpringUtil;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;

public class AliPayUtil {

	// 签名方式
	public static String SIGN_TYPE = "RSA2";

	// 字符编码格式
	public static String CHARSET = "utf-8";

	private static AlipayClient initAlipayClient(AliPayFull aliPayFull) {
//		 String gateWayUrl =
//		 SimpleUtil.payMap.get("aliPaySaxBox").equals("0")?SimpleUtil.aliPayMap.get("sBoxGateUrl"):SimpleUtil.aliPayMap.get("gateUrl");
//		 System.out.println("支付宝支付环境为:\n"+(SimpleUtil.payMap.get("aliPaySaxBox").equals("0")?"沙箱环境":"上线环境"));
		String gateWayUrl = "https://openapi.alipaydev.com/gateway.do";
		return new DefaultAlipayClient(
				gateWayUrl,
				aliPayFull.getAppID(),
				aliPayFull.getMchKey(),
				"json",
				CHARSET,
				"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4YWB0+BFbQFIMmN5BW8l9GGwtRBK6s4ApX4Ij2y565tjQiiq64kYsfJk3re7NDaMiacbklAhvYf0pThDxguW7VbpzHm1d3M8RIf3hP2+B5txU+aOyz7htfjouIN158Y8ers/Ten7r44rZvF2qWfRT610fSoaEUYOeX+KUqRzUI3EcTXe39XBimBenYjJ66zxU2wcG627E+N7/25hYG2jN/8ehdGKx2rN28iInMxWuj6tb7zY4oRIfzY9Ozn1BupbAQwltRyN+BhGnwN0LKmjRQVdPxClqDSdF+he/q+Zi4grJG5K+Ze868UQIFZMXlKH70FkZbo4608f+4sgDRfduQIDAQAB",
				// SimpleUtil.aliPayMap.get("publicKey"),
				SIGN_TYPE); // 商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
	}

	/**
	 * 生成form订单
	 * 
	 * @param aliPayFull
	 *            支付宝配置
	 * @param payInfo
	 *            订单信息
	 * @return
	 * @throws BaseException
	 */
	public static String initPayForm(AliPayFull aliPayFull, PayInfo payInfo)
			throws BaseException {
		int total = Integer.parseInt(payInfo.getTotal_fee());
		AlipayClient alipayClient = initAlipayClient(aliPayFull);
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();// 创建API对应的request
		alipayRequest.setReturnUrl(SimpleUtil.payMap.get("aliPaySynUrl"));
		alipayRequest.setNotifyUrl(SimpleUtil.payMap.get("aliPayNotiryUrl"));// 在公共参数中设置回跳和通知地址
		System.out.println("会带哦URl");
		System.out.println(alipayRequest.getReturnUrl());
		System.out.println(alipayRequest.getNotifyUrl());
		alipayRequest.setBizContent("{" + "    \"out_trade_no\":\""
				+ payInfo.getTradeNum() + "\","
				+ "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\","
				+ "    \"total_amount\":"
				+ String.valueOf(total / 100 + total % 100 * 0.01) + ","
				+ "    \"subject\":\"" + payInfo.getSubject() + "\","
				+ "    \"body\":\"" + payInfo.getDetail() + "\""
				// +
				// "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\","
				// + "    \"extend_params\":{"
				// + "    \"sys_service_provider_id\":\"2088511833207846\""
				// + "    }"
				+ "  }");// 填充业务参数
		String form = "";
		try {
			form = alipayClient.pageExecute(alipayRequest).getBody(); // 调用SDK生成表单
		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new BaseException(e,
					SpringUtil.getI18nMsg("aliPay_payForm_error"));
		}
		return form;
	}

	/**
	 * 查询支付宝订单状态
	 * 
	 * @param aliPayFull
	 *            支付宝配置
	 * @param payInfo
	 *            订单消息
	 * @return
	 */
	public static Map<String, String> queryOrder(AliPayFull aliPayFull,
			PayInfo payInfo) throws Exception {
		Map<String, String> resultMap = new HashMap<String, String>();

		AlipayClient alipayClient = initAlipayClient(aliPayFull);
		AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
		request.setBizContent("{" + "\"out_trade_no\":\""
				+ payInfo.getTradeNum() + "\"" +
				// "\"trade_no\":\"2014112611001004680073956707\"" +
				"}");
		AlipayTradeQueryResponse response = alipayClient.execute(request);
		if (response.isSuccess()) {
			// 请求返回体：{"alipay_trade_query_response":{"code":"10000","msg":"Success","buyer_logon_id":"stq***@sandbox.com","buyer_pay_amount":"0.00","buyer_user_id":"2088102170460027","buyer_user_type":"PRIVATE","invoice_amount":"0.00","open_id":"20880056007627551754882190217902","out_trade_no":"PM20171213150526","point_amount":"0.00","receipt_amount":"0.00","send_pay_date":"2017-12-13 15:12:49","total_amount":"1.00","trade_no":"2017121321001004020200257063","trade_status":"TRADE_SUCCESS"},"sign":"gmZbtU4dwMTyqCjD5/SelZQYwShr0uHrBEWZ6g0XM7TCQv2/Iyplxv4Gjb5IbtSQs2rwMkHCneTYI5DSFcWNN9GWbYl4qzBgzJP5K+IjQR3KsGVEeRS9il5KwtkLZlXyJkeTd94yq1Phg9tVfnx74xL/dT8ZoAPJZRKpS8EZbK+WhgVNtg//2mny0V9xptPIJeWDHx4Sb9Aotdh5XIbxuVq2jmoMQN9rgqUIuzatwA6sJX72ckbgsVWIgnz5J81k3NilXPmp8+HqE+RAEUEXoOQsAprj4mowmF/Bs6M9NdYu5Vgi4/2zYcviqIsFumUXT1RU45zLquhNK4Us6PQuCQ=="}
			String responseBody = response.getBody();
			resultMap.put("return_code", "1");
			resultMap.put("responseBody", responseBody);// 请求返回体，包含所有的订单返回信息
			// resultMap.put("trade_no", response.getTradeNo()); //支付宝交易号
			// resultMap.put("totalAmount", response.getTotalAmount()); //总金额
			// resultMap.put("orderId", response.getOutTradeNo()); //商户订单号
			// SimpleDateFormat format = new
			SimpleDateFormat format = new  SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
			 String send_pay_date = format.format(response.getSendPayDate());
			 resultMap.put("send_pay_date", send_pay_date); //订单发送时间

		} else {
			resultMap.put("return_code", "0");
			resultMap.put(
					"return_msg",
					response.getSubMsg() == null ? SpringUtil
							.getI18nMsg("order_result_no") : response
							.getSubMsg());
		}
		return resultMap;
	}
	
	/**
	 * 查询支付宝退款订单状态
	 * 
	 * @param aliPayFull
	 *            支付宝配置
	 * @param payInfo
	 *            订单消息
	 * @return
	 */
	public static Map<String, String> queryRefundOrder(AliPayFull aliPayFull,
			PayInfo payInfo) throws Exception {
		Map<String, String> resultMap = new HashMap<String, String>();
		
		AlipayClient alipayClient = initAlipayClient(aliPayFull);
		AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
		request.setBizContent("{" +
		"\"trade_no\":\"20150320010101001\"," +
		"\"out_trade_no\":\"2014112611001004680073956707\"," +
		"\"out_request_no\":\"2014112611001004680073956707\"" +
		"}");
		AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
		if (response.isSuccess()) {
			String responseBody = response.getBody();
			resultMap.put("return_code", "1");
			resultMap.put("responseBody", responseBody);// 请求返回体，包含所有的订单返回信息
			// resultMap.put("trade_no", response.getTradeNo()); //支付宝交易号
			// resultMap.put("totalAmount", response.getTotalAmount()); //总金额
			// resultMap.put("orderId", response.getOutTradeNo()); //商户订单号
			// SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
//			 String send_pay_date = format.format(response.get);
//			 resultMap.put("send_pay_date", send_pay_date); //订单发送时间
		} else {
			resultMap.put("return_code", "0");
			resultMap.put(
					"return_msg",
					response.getSubMsg() == null ? SpringUtil
							.getI18nMsg("order_result_no") : response
							.getSubMsg());
		}
		return resultMap;
	}

	/**
	 * 支付宝工具类验签
	 * 
	 * @param dataContent
	 *            明文
	 * @param sign
	 * @param aliPayFull
	 * @return
	 */
	public static boolean vertifyDate(String dataContent, String sign,
			AliPayFull aliPayFull) {

		if (dataContent == null || dataContent.equals("") || sign == null
				|| sign.equals(""))
			return false;
		try {
			return AlipaySignature.rsaCheck(dataContent, sign,
					aliPayFull.getPublicKey(), CHARSET, SIGN_TYPE);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 支付宝验签，重载方法
	 * @param paramMap  要验签的集合
	 * @param publicKey 支付宝公钥
	 * @return
	 */
	public static Map<String, String> vertifyDate(Map<String, String> paramMap,String publicKey){
		Map<String, String> resultMap = new HashMap<String,String>();
		if(paramMap == null || paramMap.isEmpty()){
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("decode_val_error"));
			return resultMap;
		}
		if(publicKey == null || publicKey.equals("")){
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("decode_resp_error")+"支付宝 publicKey---"+publicKey);
			return resultMap;
		}
		try {
			boolean result =  AlipaySignature.rsaCheckV1(paramMap, publicKey, CHARSET,SIGN_TYPE);
			if(result){
				//验签成功
				resultMap.put("return_code", "1");
			}else {
				resultMap.put("return_code", "0");
				resultMap.put("return_msg", SpringUtil.getI18nMsg("decode_val_error"));
			}
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("return_code", "0");
			resultMap.put("return_msg", SpringUtil.getI18nMsg("decode_val_error"));
			return resultMap;
		}
	}
	/**
	 * 支付宝订单退款
	 * 
	 * @param aliPayFull
	 *            支付宝配置
	 * @param payInfo
	 *            订单消息
	 * @return
	 */
	public static Map<String, String> refundOrder(AliPayFull aliPayFull,
			PayInfo payInfo) throws Exception {
		Map<String, String> resultMap = new HashMap<String, String>();

		AlipayClient alipayClient = initAlipayClient(aliPayFull);
		AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		request.setBizContent("{" + "\"out_trade_no\":\""
				+ payInfo.getTradeNum() + "\","
				+
				// "\"trade_no\":\"2014112611001004680073956707\"," +
				"\"refund_amount\":"
				+ changeF2Y(payInfo.getTotal_fee()) + "," + // 需要退款的金额，该金额不能大于订单金额,单位为元，支持两位小数
				"\"refund_reason\":\"商品退款\"" + "  }");
		AlipayTradeRefundResponse response = alipayClient.execute(request);
		System.out.println("撤销支付宝交易:" + payInfo.getTradeNum() + "结果为:\t"
				+ response.getBody());
		System.out.println(response.getBody());
		//body 样例 {"alipay_trade_refund_response":{"code":"10000","msg":"Success","buyer_logon_id":"stq***@sandbox.com","buyer_user_id":"2088102170460027","fund_change":"Y","gmt_refund_pay":"2017-12-15 15:52:40","open_id":"20880056007627551754882190217902","out_trade_no":"PM20171215145939","refund_fee":"1.32","send_back_fee":"0.00","trade_no":"2017121521001004020200257886"},"sign":"vgEGNv1SmxlqhRv3WiCUYAnyYfgoymYVqVXK4X+/ATxuV8Hg16xR9PxdatytCIw2+mw169Zu2QeAlBFN6O/g633uoiND2fUtLDqlf6KzRLR4DqkRaeMFgSpztpxritmT5pLq81mPbePaELBP99hufoPUj9pIwc/TNxb9ft701/zw2a1dQl+bzpSO9HJsWxJjDVY0tEJjp9DVHV3jUXcGSjv7lCpaFdzehBzF6kl7t2J9D8z/FJa9bu27YTw8svnb2zCSbRDCD3eDbXNyp0Aai6y74M0agK9jRolpOhraxHu8sJA29NvXqhSX+v9PbuykdNZqYKQx7GBPMjOfGiyVig=="}
		if (response.isSuccess()) {
			System.out.println("调用成功");
			resultMap.put("responseBody", response.getBody());
			resultMap.put("return_code", "1");
		} else {
			System.out.println("调用失败");
			resultMap.put("return_code", "0");
			resultMap.put("return_msg",
					SpringUtil.getI18nMsg("aliPay_refund_error"));
		}
		return resultMap;
	}

	/**
	 * 下载支付宝对账文件
	 * 
	 * @param aliPayFull
	 * @param date
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> downloadFile(AliPayFull aliPayFull,
			String date) throws Exception {
		Map<String, String> resultMap = new HashMap<String, String>();
		AlipayClient alipayClient = initAlipayClient(aliPayFull);
		AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
		request.setBizContent("{" + "\"bill_type\":\"trade\","
				+ "\"bill_date\":\"" + date + "\"" + "  }");
		AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient
				.execute(request);
		if (response.isSuccess()) {
			String downloadUrl = response.getBillDownloadUrl();
			resultMap.put("return_code", "1");
			resultMap.put("downloadUrl", downloadUrl);
		} else {
			resultMap.put("return_code", "0");
			resultMap.put("return_msg",
					SpringUtil.getI18nMsg("aliPay_download_error"));

		}
		return resultMap;
	}

	/**
	 * 元转分
	 * 
	 * @param amount
	 *            金额 元 支持小数点
	 * @return
	 */
	public static String changeY2F(String amount) {
		BigDecimal bigDecimal = new BigDecimal(amount);
		return String.valueOf(bigDecimal.multiply(new BigDecimal(100))
				.longValue());
	}

	/**
	 * 分转元
	 * 
	 * @param amount
	 *            金额  分 
	 * @return
	 */
	public static String changeF2Y(String amount) {
		return BigDecimal.valueOf(Long.valueOf(amount))
				.divide(new BigDecimal(100)).toString();
	}

}
